package com.hdphone.zljutils.impl;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.text.TextUtils;

import com.hdphone.zljutils.ZljUtils;
import com.hdphone.zljutils.inter.IClipboardUtil;

public class ClipboardUtilImpl implements IClipboardUtil {

    @Override
    public void copyTextToClipboard(String copyText, String toastText) {
        ClipboardManager cm = (ClipboardManager) ZljUtils.getApp().getSystemService(Context.CLIPBOARD_SERVICE);
        cm.setPrimaryClip(ClipData.newPlainText("text", copyText));
        ZljUtils.TOAST().showShortToast(toastText);
    }

    @Override
    public void copyTextToClipboard(String copyText) {
        ClipboardManager cm = (ClipboardManager) ZljUtils.getApp().getSystemService(Context.CLIPBOARD_SERVICE);
        cm.setPrimaryClip(ClipData.newPlainText("text", copyText));
    }

    @Override
    public String getTextFromClipboard(String label) {
        ClipboardManager cm = (ClipboardManager) ZljUtils.getApp().getSystemService(Context.CLIPBOARD_SERVICE);
        if (cm == null) {
            return "";
        }
        try {
            ClipData primaryClip = cm.getPrimaryClip();
            //自己代码设置的不进行请求
            if (primaryClip == null || primaryClip.getItemCount() < 1 || (primaryClip.getDescription() != null && TextUtils.equals(primaryClip.getDescription().getLabel(), label))) {
                return "";
            }
            ClipData.Item itemAt = primaryClip.getItemAt(0);
            if (itemAt != null && itemAt.getText() != null) {
                return itemAt.getText().toString();
            }
        } catch (Exception e) {
            return "";
        }
        return "";
    }

    @Override
    public void clearTextFromClipboard() {
        ClipboardManager cm = (ClipboardManager) ZljUtils.getApp().getSystemService(Context.CLIPBOARD_SERVICE);
        cm.setPrimaryClip(ClipData.newPlainText("text", null));
    }
}
